package com.suke.czx.modules.wx.handler;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.suke.czx.modules.wx.builder.TextBuilder;
import com.suke.czx.modules.wx.config.WxMpConfiguration;
import com.suke.czx.modules.wx.config.WxPayProperties;
import com.suke.czx.modules.wxadmin.entity.DkUserEntity;
import com.suke.czx.modules.wxadmin.service.DkUserService;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class SubscribeHandler extends AbstractHandler {
	@Autowired 
	private WxPayProperties wxPayProperties;

	@Autowired
	private DkUserService dkUserService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService weixinService,
			WxSessionManager sessionManager) throws WxErrorException {

		this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

		// 获取微信用户基本信息
		try {
			WxMpUser userWxInfo = weixinService.getUserService().userInfo(wxMessage.getFromUser(), null);
			if (userWxInfo != null) {
				// TODO 可以添加关注用户到本地数据库
			}
		} catch (WxErrorException e) {
			if (e.getError().getErrorCode() == 48001) {
				this.logger.info("该公众号没有获取用户信息权限！");
			}
		}
		String content = "【210天诗词精读学习计划】火热报名中!\r\n\r\n" + "🎁全勤学习，返129元现金\r\n"
				+ "🌹奖励不断：每学习45天，免费领取精品正版图书一套，共计4套\r\n\r\n"
				+ "<a href='http://"+wxPayProperties.getHost()+"/x_springboot/wx/redirect/"+wxPayProperties.getAppId()+"?url=http://"+wxPayProperties.getHost()+"/x_springboot/wx/base/"+wxPayProperties.getAppId()+"/rout?p=pay_1_1&isshow=1'>☞戳我报名，古诗不用背！</a>"
				+ "\r\n"
				+ "<a href='http://"+wxPayProperties.getHost()+"/x_springboot/wx/redirect/"+wxPayProperties.getAppId()+"?url=http://"+wxPayProperties.getHost()+"/x_springboot/wx/base/"+wxPayProperties.getAppId()+"/rout?p=pay_1_1&isshow=1'>☞戳我报名，听完自然会!</a>"
				+ "\r\n\r\n" + "已报名？点击下方「今日阅读」进行第一天学习！\r\n"
			    + " ↓  ↓  ↓";

		new Thread(new Runnable() {
			public void run() {
				// 演示10s秒钟发送模板消息
				try {
					WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxPayProperties.getAppId());
					DkUserEntity user = dkUserService.queryObject(wxMessage.getFromUser(),false);
					if(null==user){
						WxMpUser  wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
						user = new DkUserEntity();
						user.setOpenid(wxMpUser.getOpenId());
						user.setCreatetime(new Date());
						user.setHeadimg(wxMpUser.getHeadImgUrl());
						user.setNickname(wxMpUser.getNickname());
						user.setState(0);
						dkUserService.save(user);
						return;
					}
					//判断用户是否购买
					if(user.getState()!=1){
						return;
					}
					Thread.sleep(5000);
					// 发送模板消息
					WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().toUser(wxMessage.getFromUser())
							.templateId(wxPayProperties.getTidBuySuccess()).build();
					templateMessage.addData(new WxMpTemplateData("first", "您已成功订购以下课程\r\n\r\n", "#000000"));
					templateMessage.addData(new WxMpTemplateData("keyword1", "《精读诗词·210天学习计划》", "#000000"));
					templateMessage.addData(new WxMpTemplateData("keyword2", user.getStartTime(), "#000000"));
					templateMessage.addData(new WxMpTemplateData("keyword3", "长期有效，可以反复听", "#000000"));
					templateMessage.addData(
							new WxMpTemplateData("remark", "点击下方『今日阅读』即刻开启今天的课程，记得学习哟~\r\n\r\n↓↓↓", "#000000"));
					wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();

		try {
			return new TextBuilder().build(content, wxMessage, weixinService);
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
		}

		return null;
	}
}
